package container_cmds

import (
	"fmt"
	"strconv"

	"atomgit.com/openlinksaas/devc/utils"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/client"
	"github.com/spf13/cobra"
)

type FindResult struct {
	ContainerId string `json:"containerId"`
	State       string `json:"state"`
	ServerPort  uint16 `json:"serverPort"`
	DevCfg      string `json:"devCfg"`
	RepoPath    string `json:"repoPath"`
}

var findCmd = &cobra.Command{
	Use: "find",
	PreRunE: func(cmd *cobra.Command, args []string) error {
		if len(args) != 1 {
			return fmt.Errorf("need param [repoId]")
		}
		return nil
	},
	RunE: runFind,
}

func runFind(cmd *cobra.Command, args []string) error {
	repoId := args[0]

	cli, err := client.NewClientWithOpts(client.FromEnv)
	if err != nil {
		return err
	}

	filterArgs := filters.NewArgs()
	filterArgs.Add("label", fmt.Sprintf("repoId=%s", repoId))
	filterArgs.Add("label", "provider=linksaas")

	containerItemList, err := cli.ContainerList(cmd.Context(), types.ContainerListOptions{
		All:     true,
		Filters: filterArgs,
	})
	if err != nil {
		return err
	}

	if len(containerItemList) == 0 {
		utils.PrintResult(&FindResult{})
		return nil
	}

	serverPortStr := "0"
	devCfg := "{}"
	repoPath := ""
	for k, v := range containerItemList[0].Labels {
		if k == "serverPort" {
			serverPortStr = v
		} else if k == "devCfg" {
			devCfg = v
		} else if k == "repoPath" {
			repoPath = v
		}
	}

	serverPort, _ := strconv.Atoi(serverPortStr)

	utils.PrintResult(&FindResult{
		ContainerId: containerItemList[0].ID,
		State:       containerItemList[0].State,
		ServerPort:  uint16(serverPort),
		DevCfg:      devCfg,
		RepoPath:    repoPath,
	})
	return nil
}
